package com.sk.bilibili.apiMapper;

import com.sk.bilibili.apiMapper.component.ApiMapperProxy;
import com.sk.bilibili.apiMapper.component.HttpSender;
import com.sk.bilibili.apiMapper.component.JsonHandler;
import com.sk.bilibili.apiMapper.component.RequestHandler;
import com.sk.bilibili.apiMapper.component.converter.DefaultConverter;
import com.sk.bilibili.apiMapper.component.converter.IntegerConverter;
import com.sk.bilibili.apiMapper.component.converter.LongConverter;
import com.sk.bilibili.apiMapper.component.methodHandler.GetMethodHandler;
import com.sk.bilibili.apiMapper.component.methodHandler.PostMethodHandler;
import com.sk.bilibili.apiMapper.interfaces.MethodHandler;
import com.sk.bilibili.apiMapper.interfaces.StringConverter;
import okhttp3.OkHttpClient;

import java.lang.reflect.Proxy;

/**
 * @author 邵康
 * @date 2021/7/10 20:28
 */
public class ApiMapper {

    public ApiMapper() {
        create();
        initComponent();
    }

    private void create() {
        requestHandler=new RequestHandler();
        httpSender=new HttpSender();
        jsonHandler=new JsonHandler();
    }

    private void initComponent() {
        httpSender.addMethodHandler(new GetMethodHandler());
        httpSender.addMethodHandler(new PostMethodHandler());
        requestHandler.setHttpSender(httpSender);
        requestHandler.setJsonHandler(jsonHandler);
        addStringConverter(new IntegerConverter());
        addStringConverter(new LongConverter());
        addStringConverter(new DefaultConverter());
        addMethodHandler(new GetMethodHandler());
        addMethodHandler(new PostMethodHandler());
    }

    public void addMethodHandler(MethodHandler methodHandler){
        httpSender.addMethodHandler(methodHandler);
    }

    private RequestHandler requestHandler;
    private HttpSender httpSender;
    private JsonHandler jsonHandler;
    private static final ClassLoader DEFAULT_CLASS_LOADER=ApiMapper.class.getClassLoader();

    public void addStringConverter(StringConverter stringConverter){
        jsonHandler.addStringConverter(stringConverter);
    }

    //  用于 初始化  若  用户没有自定义  需要 初始化 默认配置
    public void init() {
        httpSender.initOkHttpClient();
        jsonHandler.init();
    }

    public void setLogInfo(boolean logInfo) {
        httpSender.setLogInfo(logInfo);
    }

    public void setOkHttpClient(OkHttpClient okHttpClient) {
        httpSender.setOkHttpClient(okHttpClient);
    }

    public <T> T create(Class<T> mapperClass) {
        return (T) Proxy.newProxyInstance(DEFAULT_CLASS_LOADER, new Class[]{mapperClass},
                new ApiMapperProxy(mapperClass, requestHandler));
    }

}











